<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>

        <template #right>
          <el-button v-permission="'p-em-excel-upload'" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-permission="'p-em-excel-export'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-permission="'p-em-add'" type="primary" size="small" @click="addFn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoding" style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column type="index" :index="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template #default="{row}">
              <img v-imgerror="defaultImage" :src="row.staffPhoto ||defaultImage" alt="" srcset="" class="imgimg">

            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="enableState" :formatter="formatter" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间">
            <template #default="{row}">
              {{ formateTime(row.timeOfEntry) }}

            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button v-permission="'p-em-look'" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="showRoleDialogFn(row.id)">分配角色</el-button>
              <el-button v-permission="'p-em-del'" type="text" size="small" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="from.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="from.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- sync对子组件进行放权 -->
      <addemployee :show-dialog.sync="showDialog" />
      <assignrole :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
// 导入处理聘用形式文件
import employees from '@/constant/employees'
import { getEmployeesSimleList, delEmployeesSimleApi } from '@/api/employees.js'
import addemployee from './components/add-employee.vue'
// import EnployeeFn from '@/constant/employees'
import assignrole from './components/assign-role.vue'
import { mapGetters } from 'vuex'
// 使用mixins步奏
// 1.先导入

import permission from '@/mixins/permission'
export default {
  name: 'Employees',
  components: {
    addemployee,
    assignrole
  },
  // 步骤2 混入
  mixins: [permission], // 第三步就可以正常使用了，上面用的自定义属性写法写法
  data() {
    return {
      userId: '',
      showRoleDialog: false,
      defaultImage: 'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      showDialog: false,
      isLoding: false,
      list: [],
      total: null,
      from: {
        page: 1,
        size: 10
      }
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmployeesSimleListFn()
  },
  methods: {
    // hasPermission(permission) {
    //   return this.roles.points.includes(permission)
    // },

    showRoleDialogFn(id) {
      // 对userId进行赋值然后传给子组件
      this.userId = id
      console.log(this.userId)
      this.showRoleDialog = true
    },
    // 导出
    async handleDownload() {
      // this.downloadLoading = true
      this.from.size = this.total// 将总数赋值给它
      this.from.page = 1// 一页打印所有
      const { data: { rows }} = await getEmployeesSimleList(this.from)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const formatData = this.formatJson(rows, headersArr, headersRelations)

      console.log(formatData)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr,
          // data要是一个二维数组
          data: formatData,
          filename: '员工信息', // 导出表的文件名
          autoWidth: true,
          bookType: 'xlsx'// 后缀名
        })
        // this.downloadLoading = false
      })
    },
    formatJson(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach(item => {
        const tempArr = []
        headersArr.forEach(header => {
          const englishKey = headersRelations[header]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const hirType = employees.hireType
            const obj = hirType.find(item => item.id === +value)
            return obj ? obj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.formateTime(value)
          }// 处理日期

          // tempArr.push(item[englishKey])
          tempArr.push(value)
        })
        list.push(tempArr)
      })
      return list
    },

    // 新增
    addFn() {
      this.showDialog = true
    },
    // 处理日期函数
    formateTime(value) {
      return value ? dayjs(value).format('YYYY-MM-DD') : ''
    },
    // 处理聘用形式
    formatter(row, column, cellValue) {
      const hireType = employees.hireType
      const obj = hireType.find((item) => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },

    // 列表渲染
    async getEmployeesSimleListFn() {
      this.isLoding = true
      const res = await getEmployeesSimleList(this.from)
      this.list = res.data.rows
      this.total = res.data.total
      this.isLoding = false
      console.log(res)
    },
    // 删除接口
    async delFn(id) {
      this.$confirm('你确定要删除吗', '删除就没有了').then(async() => {
        await delEmployeesSimleApi(id)
        if (this.list.length === 1 && this.from.page > 1) {
          this.from.page--
        }

        this.$message.success('删除成功了呦')
        this.getEmployeesSimleListFn()
      }).catch(() => {

      })

      // const res =
      // console.log(res)
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.from.size = val
      this.getEmployeesSimleListFn()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.from.page = val
      this.getEmployeesSimleListFn()
    },
    index(index) {
      return this.from.size * (this.from.page - 1) + index + 1
    }

  }
}
</script>

<style lang="scss" scoped>

    .imgimg {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }

</style>
